package com.simple.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.simple.action.Interfaces.Action;
import com.simple.entity.ModelAndView;
import com.simple.entity.XmlBean;
import com.simple.utils.ActionForm;
import com.simple.utils.FullForm;

/**
 * mvc框架实现类
 * @author 李凯
 * @version v-1.0
 * @date 2017-8-20
 * */
public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8;pageEncoding=UTF-8");
		request.setCharacterEncoding("UTF-8");
		String path = request.getServletPath().split("\\.")[0];
		Map<String,XmlBean> map = (Map<String,XmlBean>)getServletContext().getAttribute("simple");
		XmlBean xml = map.get(path);
		String formclass = xml.getFormClass();
		ActionForm form = FullForm.full(formclass, request);
		String actiontype = xml.getActionClass();
		Action action = null;
		ModelAndView model = null;
		try {
			Class<?> clazz = Class.forName(actiontype);
			action = (Action)clazz.newInstance();
			model = action.execute(request, response, 
					form, xml.getActionForward());
		}catch (Exception e) {
			e.printStackTrace();
		}
		String url = model.getUrl();
		String formName = model.getEntity().getClass().toString();
		String[] ar = formName.split("\\.");
		String formRealName = "";
		for(int i = 0;i < ar.length; i++) {
			if(ar.length - 1 == i) {
				formRealName = ar[i];
			}
		}
		String key = "";
		for(int j = 0; j < formRealName.length(); j++) {
			if(j == 0) {
				key += String.valueOf(formRealName.charAt(j)).toLowerCase();
			}else {
				key += String.valueOf(formRealName.charAt(j));
			}
		}
		request.setAttribute(key, model.getEntity());
		RequestDispatcher dis = request.getRequestDispatcher(url);
		dis.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
